package com.wjs.gulimall.gulimallorder.controller;

import com.atguigu.common.exception.NoStockException;
import com.wjs.gulimall.gulimallorder.service.OrderService;
import com.wjs.gulimall.gulimallorder.vo.OrderConfrimVo;
import com.wjs.gulimall.gulimallorder.vo.OrderSubmitVo;
import com.wjs.gulimall.gulimallorder.vo.SubmitOrderResponseVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.concurrent.ExecutionException;

@Controller
public class OrderWebController {
    @Autowired
    private OrderService orderService;

    /**
     * 去订单确认页
     */
    @GetMapping("/toTrade")
    public String toTrade(Model model) throws ExecutionException, InterruptedException {
        OrderConfrimVo orderConfrimVo=orderService.confirmOrder();
        model.addAttribute("orderConfirmData",orderConfrimVo);
        return "confirm";
    }

    /**
     * 下单
     * @param vo
     * @return
     */
    @PostMapping("/submitOrder")
    public String subimtOrder(OrderSubmitVo vo, Model model, RedirectAttributes redirectAttributes){
        // 下单成功返回到支付页
        try {
            SubmitOrderResponseVo resp=orderService.subimtOrder(vo);
            if(resp.getCode()==0){
                //下单成功来到支付选择页
                model.addAttribute("submitOrderResp",resp);
                return "pay";
            }else {
                // 根据状态码验证对应的状态
                String msg = "下单失败";
                switch (resp.getCode()) {
                    case 1: msg += "订单信息过期，请刷新后再次提交"; break;
                    case 2: msg += "订单商品价格发生变化，请确认后再次提交"; break;
                    case 3: msg += "库存锁定失败，商品库存不足"; break;
                }
                //下单失败来到
                redirectAttributes.addFlashAttribute("msg",msg);
                return "redirect:http://order.gulimall.com/toTrade";
            }
        } catch (Exception e) {
            if (e instanceof NoStockException) {
                String message = ((NoStockException)e).getMessage();
                redirectAttributes.addFlashAttribute("msg",message);
            }
            return "redirect:http://order.gulimall.com/toTrade";
        }
    }
}
